package cn.zwx.member.svc.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.zwx.common.mybatis.query.LambdaQueryWrapperX;
import cn.zwx.member.svc.domain.entity.MemberConfigEntity;
import cn.zwx.member.svc.dto.MemberConfigSaveDTO;
import cn.zwx.member.svc.mapper.MemberConfigMapper;
import cn.zwx.member.svc.service.MemberConfigService;
import cn.zwx.member.svc.vo.MemberConfigVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author zhangwenxue
 */
@Service
public class MemberConfigServiceImpl implements MemberConfigService {

    @Resource
    private MemberConfigMapper mapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveConfig(MemberConfigSaveDTO dto) {
        // 查询是否存在信息
        MemberConfigVO config = this.getConfig();
        if (config != null){
            mapper.delete(new LambdaQueryWrapperX<>());
        }
        MemberConfigEntity entity = new MemberConfigEntity();
        BeanUtils.copyProperties(dto,entity);
        int inserted = mapper.insert(entity);
        return inserted == 1;
    }

    @Override
    public MemberConfigVO getConfig() {
        // 查询配置信息
        List<MemberConfigEntity> list = mapper.selectList();
        if (CollectionUtils.isEmpty(list)){
            return null;
        }
        // 返回参数封装
        MemberConfigEntity memberConfig = CollUtil.getFirst(list);
        MemberConfigVO configVO = new MemberConfigVO();
        configVO.setId(memberConfig.getId());
        configVO.setPointTradeDeductMaxPrice(memberConfig.getPointTradeDeductMaxPrice());
        configVO.setPointTradeDeductUnitPrice(memberConfig.getPointTradeDeductUnitPrice());
        configVO.setPointTradeDeductEnable(memberConfig.getPointTradeDeductEnable());
        configVO.setPointTradeGivePoint(memberConfig.getPointTradeGivePoint());
        return configVO;
    }
}
